<template>
	<view class="diary-write-page">
		<view class="content">
			<input class="title-input" placeholder="请输入标题" v-model="title" />

			<view class="date-picker">
				<text>日期：</text>
				<picker mode="date" :value="date" @change="onDateChange">
					<view class="date-display">{{ date }}</view>
				</picker>
			</view>

			<view class="mood-selector">
				<text>心情：</text>
				<view class="mood-options">
					<view v-for="mood in moodOptions" :key="mood.value" class="mood-item"
						:class="{ selected: currentMood === mood.value }" @click="selectMood(mood.value)">
						<text>{{ mood.label }}</text>
					</view>
				</view>
			</view>

			<!-- 添加文本格式选择 -->
			<view class="format-selector">
				<text>格式：</text>
				<view class="format-options">
					<view class="format-item" :class="{ selected: formatType === 'normal' }"
						@click="selectFormat('normal')">
						<text>常规</text>
					</view>
					<view class="format-item" :class="{ selected: formatType === 'markdown' }"
						@click="selectFormat('markdown')">
						<text>Markdown</text>
					</view>
				</view>
			</view>

			<!-- 根据选择的格式显示不同的输入区域 -->
			<view v-if="formatType === 'normal'">
				<textarea class="content-textarea" placeholder="记录你的美好时光..." v-model="content" auto-height
					maxlength="1000" />
				<view class="char-count">{{ content.length }}/1000</view>
			</view>

			<view v-else class="markdown-container">
				<textarea class="content-textarea markdown-input" placeholder="使用Markdown语法记录你的美好时光..."
					v-model="content" auto-height maxlength="1000" />
				<view class="char-count">{{ content.length }}/1000</view>
				<view class="preview-toggle" @click="togglePreview">
					{{ showPreview ? '隐藏预览' : '预览' }}
				</view>
				<view v-show="showPreview" class="markdown-preview" v-html="renderedMarkdown"></view>
			</view>

			<view class="image-upload">
				<text>图片：</text>
				<view class="image-list">
					<view v-for="(image, index) in ossList" :key="index" class="image-item">
						<image :src="image" mode="aspectFill" />
						<view class="delete-btn" @click="deleteImage(index)">×</view>
					</view>
					<view class="add-image-btn" @click="chooseImage" v-if="images.length < 9">
						+
					</view>
				</view>
			</view>
		</view>

		<view class="footer">
			<button class="save-btn" @click="saveDiary">保存</button>
			<button class="cancel-btn" @click="cancel">取消</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch
	} from 'vue'
	// 引入marked库用于Markdown解析
	import {
		marked
	} from "marked"
	import request from '../../utils/request'
	import {
		useUserStore
	} from '../../store/user'
	import dayjs from 'dayjs'
	import {
		upload
	} from '../../utils/upload'
	import {
		onShow
	} from '@dcloudio/uni-app'


	// 响应式数据
	const userStore = useUserStore()
	const recordTime = dayjs().format("YYYY-MM-DD")
	const title = ref('')
	const content = ref('')
	const date = ref(new Date().toISOString().slice(0, 10))
	const currentMood = ref('happy')
	const images = ref([])
	// 新增格式类型和预览开关
	const formatType = ref('normal') // 'normal' 或 'markdown'
	const showPreview = ref(false) // 是否显示Markdown预览

	// 心情选项
	const moodOptions = [{
			value: 'happy',
			label: '😊'
		},
		{
			value: 'sad',
			label: '😢'
		},
		{
			value: 'angry',
			label: '😠'
		},
		{
			value: 'excited',
			label: '🤩'
		},
		{
			value: 'calm',
			label: '😌'
		}
	]

	// 计算属性：渲染Markdown内容
	const renderedMarkdown = computed(() => {
		if (formatType.value === 'markdown' && content.value) {
			// 设置marked选项以增强安全性
			marked.setOptions({
				breaks: true, // 启用换行符
				gfm: true // 启用GitHub Flavored Markdown
			})
			return marked(content.value)
		}
		return ''
	})

	// 日期选择
	const onDateChange = (e) => {
		date.value = e.detail.value
	}

	// 选择心情
	const selectMood = (mood) => {
		currentMood.value = mood
	}

	// 选择文本格式
	const selectFormat = (format) => {
		formatType.value = format
	}

	// 切换Markdown预览
	const togglePreview = () => {
		showPreview.value = !showPreview.value
	}
	const tempImgList = ref([])
	const ossList = ref([])
	// 选择图片
	const chooseImage = () => {
		uni.chooseImage({
			count: 9 - images.value.length,
			success: (res) => {
				images.value = [...images.value, ...res.tempFilePaths]
				for (let img of images.value) {
					if (tempImgList.value.includes(img)) {
						continue
					}
					upload(img).then((val) => {
						ossList.value.push(val)
						tempImgList.value.push(img)
					})
				}
			}
		})
	}


	// 删除图片
	const deleteImage = (index) => {
		images.value.splice(index, 1)
		ossList.value.splice(index, 1)

	}

	// 监听内容变化，限制字数
	watch(content, (newContent) => {
		if (newContent.length > 1000) {
			content.value = newContent.substring(0, 1000)
		}
	})

	const reset = () => {
		title.value = ''
		content.value = ''
		currentMood.value = 'happy'
		images.value = []
		formatType.value = "normal"
	}

	const setById = (val) => {
		title.value = val.title
		content.value = val.content
		currentMood.value = val.mood
		images.value = val.imgs ? val.imgs.split(',') : []
		ossList.value = val.imgs ? val.imgs.split(',') : []
		formatType.value = val.textType
		diaryId.value = val.id
	}

	// 保存日记
	const saveDiary = () => {
		if (!title.value.trim()) {
			uni.showToast({
				title: '请输入标题',
				icon: 'none'
			})
			return
		}

		if (!content.value.trim()) {
			uni.showToast({
				title: '请输入内容',
				icon: 'none'
			})
			return
		}

		if (content.value.length > 1000) {
			uni.showToast({
				title: '内容不能超过1000字',
				icon: 'none'
			})
			return
		}

		// 这里可以调用API保存日记
		const diaryData = {
			title: title.value,
			content: content.value,
			recordTime: dayjs(date.value).format('YYYY-MM-DD') + " " + dayjs().format('HH:mm:ss'),
			mood: currentMood.value,
			imgs: ossList.value.toString(),
			textType: formatType.value, // 保存格式类型
			userId: userStore.id,	
			id: diaryId.value
		}
		console.log("diaryData", diaryData)

		request.post("/diary/save", diaryData).then(response => {
			if (response.code === 200) {
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				})

				uni.showModal({
					title: '提示',
					content: '要再记录一篇日记吗？',
					cancelText: "查看日记",
					success: function(res) {
						if (res.confirm) {
							reset()
						} else if (res.cancel) {
							uni.setStorageSync(`update`, 1);
							uni.switchTab({
								url: "/pages/index/index?update=1"
							})
							reset()
						}
					}
				});
			} else {
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			}
		})
	}

	// 取消操作
	const cancel = () => {
		uni.navigateBack()
	}

	const loading = ref(false)

	const diaryId = ref()

	const loadDiaryDetail = async (id) => {
		try {
			loading.value = true
			const response = await request.get(`/diary/detailById/${id}`)

			if (response.code === 200) {
				setById(response.data)

			} else {
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('加载日记详情失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}
	onShow(() => {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		if (currentPage.options.id) {
			loadDiaryDetail(currentPage.options.id)
		}
	})
</script>

<style scoped lang="scss">
	.diary-write-page {
		padding: 20rpx;
		background: linear-gradient(135deg, rgba(245, 236, 220, 0.8) 0%, rgba(240, 225, 205, 0.8) 100%);
		min-height: 100vh;
		font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
	}

	.content {
		background: rgba(255, 255, 255, 0.9);
		padding: 25rpx;
		border-radius: 15rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(139, 69, 19, 0.1);
	}

	.title-input {
		border: 1rpx solid #d2b48c;
		padding: 20rpx;
		border-radius: 10rpx;
		margin-bottom: 25rpx;
		font-size: 28rpx;
		background: rgba(255, 255, 255, 0.7);
		color: #8b4513;
	}

	.title-input::placeholder {
		color: #bca68a;
	}

	.date-picker {
		display: flex;
		align-items: center;
		margin-bottom: 25rpx;
		font-size: 28rpx;
		color: #8b4513;
	}

	.date-display {
		border: 1rpx solid #d2b48c;
		padding: 15rpx 20rpx;
		border-radius: 10rpx;
		flex: 1;
		color: #8b4513;
		background: rgba(255, 255, 255, 0.7);
		margin-left: 15rpx;
	}

	.mood-selector,
	.format-selector {
		margin-bottom: 25rpx;
		font-size: 28rpx;
		color: #8b4513;
	}

	.mood-options,
	.format-options {
		display: flex;
		flex-wrap: wrap;
		margin-top: 15rpx;
		gap: 15rpx;
	}

	.mood-item,
	.format-item {
		padding: 10rpx 20rpx;
		border: 1rpx solid #d2b48c;
		border-radius: 20rpx;
		background: rgba(210, 180, 140, 0.2);
		color: #8b4513;
		font-size: 26rpx;
		transition: all 0.3s ease;
	}

	.mood-item.selected,
	.format-item.selected {
		border-color: #c19a6b;
		background: linear-gradient(135deg, #d2b48c, #c19a6b);
		color: #fff;
		transform: scale(1.05);
	}

	.content-textarea {
		width: 100%;
		min-height: 200rpx;
		border: 1rpx solid #d2b48c;
		padding: 20rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
		margin-bottom: 15rpx;
		box-sizing: border-box;
		background: rgba(255, 255, 255, 0.7);
		color: #8b4513;
	}

	.content-textarea::placeholder {
		color: #bca68a;
	}

	.markdown-container {
		position: relative;
	}

	.markdown-input {
		margin-bottom: 10rpx;
	}

	.char-count {
		text-align: right;
		font-size: 24rpx;
		color: #bca68a;
		margin-bottom: 15rpx;
	}

	.preview-toggle {
		display: inline-block;
		padding: 10rpx 20rpx;
		background: rgba(210, 180, 140, 0.3);
		border-radius: 6rpx;
		font-size: 24rpx;
		color: #8b4513;
		margin-bottom: 20rpx;
		border: 1rpx solid #d2b48c;
	}

	.markdown-preview {
		min-height: 200rpx;
		padding: 20rpx;
		background: rgba(245, 240, 230, 0.7);
		border-radius: 10rpx;
		border: 1rpx solid #d2b48c;
		font-size: 28rpx;
		white-space: pre-wrap;
		color: #8b4513;
		margin-bottom: 20rpx;
	}

	/* Markdown预览样式 */
	.markdown-preview h1 {
		font-size: 42rpx;
		font-weight: bold;
		margin: 20rpx 0;
		color: #8b4513;
	}

	.markdown-preview h2 {
		font-size: 38rpx;
		font-weight: bold;
		margin: 18rpx 0;
		color: #8b4513;
	}

	.markdown-preview h3 {
		font-size: 34rpx;
		font-weight: bold;
		margin: 16rpx 0;
		color: #8b4513;
	}

	.markdown-preview p {
		margin: 16rpx 0;
		line-height: 1.6;
		color: #8b4513;
	}

	.markdown-preview ul,
	.markdown-preview ol {
		padding-left: 40rpx;
		margin: 16rpx 0;
		color: #8b4513;
	}

	.markdown-preview li {
		margin-bottom: 10rpx;
		color: #8b4513;
	}

	.markdown-preview code {
		background-color: #f0f0f0;
		padding: 4rpx 8rpx;
		border-radius: 4rpx;
		font-family: monospace;
	}

	.markdown-preview pre {
		background-color: #f0f0f0;
		padding: 20rpx;
		border-radius: 10rpx;
		overflow: auto;
		margin: 20rpx 0;
	}

	.markdown-preview blockquote {
		border-left: 6rpx solid #d2b48c;
		padding-left: 20rpx;
		margin: 20rpx 0;
		color: #666;
	}

	.image-upload {
		font-size: 28rpx;
		color: #8b4513;
		margin-top: 10rpx;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
		margin-top: 15rpx;
		gap: 15rpx;
	}

	.image-item {
		position: relative;
		width: 140rpx;
		height: 140rpx;
	}

	.image-item image {
		width: 100%;
		height: 100%;
		border-radius: 10rpx;
		border: 1rpx solid #d2b48c;
	}

	.delete-btn {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: #ff6b6b;
		border-radius: 50%;
		color: #fff;
		text-align: center;
		line-height: 40rpx;
		font-size: 24rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
	}

	.add-image-btn {
		width: 140rpx;
		height: 140rpx;
		border: 1rpx dashed #d2b48c;
		border-radius: 10rpx;
		text-align: center;
		line-height: 140rpx;
		font-size: 60rpx;
		color: #bca68a;
		background: rgba(255, 255, 255, 0.5);
	}

	.footer {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0;
		gap: 20rpx;
	}

	.save-btn,
	.cancel-btn {
		flex: 1;
		border-radius: 30rpx;
		padding: 20rpx;
		font-size: 30rpx;
		font-weight: bold;
		border: none;
		color: #8b4513;
		box-shadow: 0 4rpx 12rpx rgba(139, 69, 19, 0.2);
	}

	.save-btn {
		background: linear-gradient(135deg, #d2b48c, #c19a6b);
	}

	.cancel-btn {
		background: linear-gradient(135deg, #e0d0b8, #d2b48c);
	}

	.save-btn:active,
	.cancel-btn:active {
		transform: scale(0.98);
	}
</style>